<template>
  <div class="h5-page">
    <div class="h5-page-body">
      <Description
        size="middle"
        title="出库单信息"
        :bordered="false"
        :column="1"
        :data="data"
        :schema="orderSchema"
      />
      <div class="pad-10">
        <Space direction="vertical">
          <Card>
            <Descriptions title="司机信息" :column="2">
              <DescriptionsItem label="司机姓名">{{ data.driverName }}</DescriptionsItem>
              <DescriptionsItem label="车牌">{{ data.vehicleNo }}</DescriptionsItem>
              <DescriptionsItem label="身份证">{{ data.driverIdCard }}</DescriptionsItem>
              <DescriptionsItem label="车辆类型">{{ typeObj[data.vehicleModel] }}</DescriptionsItem>
              <DescriptionsItem label="电话">{{ data.driverPhone }}</DescriptionsItem>
              <DescriptionsItem label="运量(吨)">{{ data.goodsWeight }}</DescriptionsItem>
            </Descriptions>
          </Card>
          <Card title="运输信息" :bordered="false">
            <Row>
              <Col :span="11">
                <!-- <p>{{ data.consigneeProvince }}{{ data.consigneeCity }} {{ data.consigneeArea }}</p> -->
                <p>{{ data.consigneeAddress }}</p>
              </Col>
              <Col :span="2">
                <ShoppingCartOutlined style="color: rgb(245 154 35); font-size: 30px" />
              </Col>
              <Col :span="11" style="padding-left: 10px">
                <!-- <p>{{ data.receiverProvince }}{{ data.receiverCity }} {{ data.receiverArea }}</p> -->
                <p>{{ data.receiverAddress }}</p>
              </Col>
            </Row>
          </Card>

          <Table :dataSource="goodsList" :columns="columns" :pagination="false" />
          <!-- <BasicTable @register="registerTable" /> -->

          <Card title="回单上传" :bordered="false">
            <div class="img-list-body">
              <Upload
                v-model:file-list="fileList"
                action="/api/eslogis-tps/userFiles/upload"
                list-type="picture-card"
                :headers="{
                  Authorization: `Bearer ${tokenH5}`,
                }"
                :data="uploadParams"
                :before-upload="beforeUpload"
                :showUploadList="true"
                :disabled="data.status != 40"
                name="file"
                @preview="handlePreview"
                @remove="handleRemove"
              >
                <div v-if="fileList.length < 8">
                  <plus-outlined />
                  <div style="margin-top: 8px">上传</div>
                </div>
              </Upload>
            </div>
          </Card>

          <div style="padding-bottom: 50px">
            <p>审核提示：</p>
            <p> 1.司机务必现场拍照（送货单）上传附件</p>
            <p> 2.上传单据必须要有签收人和司机两人的签名</p>
            <p> 3.单据上必须备注货物牌号、数量、签收量、是否破损及额外收费等情况</p>
          </div>
        </Space>
      </div>
    </div>

    <div class="fix-bottom">
      <a-button :loading="loading" type="primary" @click="handleOutBound">提交</a-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
  import {
    Card,
    Col,
    Row,
    Space,
    Upload,
    UploadProps,
    message,
    Descriptions,
    DescriptionsItem,
    Table,
  } from 'ant-design-vue';
  import { PlusOutlined, ShoppingCartOutlined } from '@ant-design/icons-vue';
  // import { BasicTable, useTable } from '@/components/Table';
  import { Description } from '@/components/Description';
  import { orderSchema } from './scheme';
  import { useRouter } from 'vue-router';
  import { removeTokenH5, setTokenH5 } from '@/utils/cookie';

  // import { getDeliveryDetails, getDeliveryReceiptDetail } from '@/api/waybillManagement';
  import {
    delH5FileApi,
    getDeliveryDetailsH5,
    getDeliveryReceiptDetailH5,
    getUserFilesH5,
    shippingOrderSignFlow,
  } from './service';

  const typeObj = { 1: '挂车', 2: '厢式车', 3: '其他', 5: 'SUV' };

  // let list: any[] = reactive([]);
  const data: any = ref({});
  const tokenH5: any = ref('');
  const uploadParams = ref({});
  const shippingOrderId: any = ref('');
  const fileLabel = 'sign';
  const fileList: any = ref([]);
  const loading = ref(false);
  const goodsList: any = ref([]);
  watch(
    () => fileList,
    (val) => {
      console.log('fileList', val);
    },
  );
  const columns = [
    {
      title: '交货计划号',
      dataIndex: 'deliveryCode',
      width: 100,
    },

    {
      title: '牌号',
      dataIndex: 'goodsName',
      width: 130,
    },
    {
      title: '批次号',
      dataIndex: 'goodsBatch',
      width: 100,
    },
    {
      title: '净重',
      dataIndex: 'goodsWeight',
      width: 60,
    },
  ];

  // const [registerTable, { setTableData }] = useTable({
  //   title: '货物信息',
  //   columns,
  //   immediate: false,
  //   pagination: false,
  //   showIndexColumn: false,
  //   size: 'small',
  //   maxHeight: 200,
  //   scroll: { x: true },
  // });

  onMounted(() => {
    // 打印
    const router = useRouter();
    const { token, shippingId } = router.currentRoute.value.query;
    console.log('router:', router.currentRoute.value.query);
    console.log('token', token);
    console.log('shippingId', shippingId);
    shippingOrderId.value = shippingId;
    tokenH5.value = token;
    setTokenH5(token);
    getOrderInfo(shippingId);
    getGoodsList(shippingId);
  });

  onBeforeUnmount(() => {
    removeTokenH5();
  });

  // 获取运单详情
  function getOrderInfo(id) {
    getDeliveryReceiptDetailH5({ id }).then((res) => {
      console.log('getDeliveryReceiptDetail', res);
      data.value = res;
      uploadParams.value = {
        batchId: res.batchId,
        configCode: 'eslogis_order',
        label: fileLabel,
      };

      getUserFiles(uploadParams);
    });
  }

  // 获取已上传文件列表
  function getUserFiles(params) {
    getUserFilesH5(params.value).then((res) => {
      console.log('getUserFilesH5', res);
      const temp = res.map((item) => {
        return {
          ...item,
          uid: item.id,
          name: item.fileName,
          url: item.fileUrl,
          status: 'done',
        };
      });

      fileList.value = temp;
    });
  }

  // 获取货物列表
  function getGoodsList(id) {
    getDeliveryDetailsH5({ id }).then((res) => {
      console.log('getDeliveryDetails', res);
      goodsList.value = res;
      // setTableData(res);
    });
  }

  // 预览
  function handlePreview(val) {
    console.log('handlePreview', val);
  }

  const beforeUpload = (file: UploadProps['fileList'][number]) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('请选择图片上传!');
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('图片最大选择10MB!');
    }
    return isJpgOrPng && isLt10M;
  };

  function handleRemove(item) {
    let id = '';
    if (item.id) {
      id = item.id;
    } else {
      id = item.response.data.id;
    }

    console.log('id', id);
    // return;
    if (id) {
      delH5FileApi(id).then((res) => {
        console.log(res);
      });
    }
  }

  // 出库
  function handleOutBound() {
    console.log('fileList', fileList.value.length);
    // return;
    if (data.value.status != 40) {
      message.error('当前状态无法签收！');
      return;
    }

    if (fileList.value.length === 0) {
      message.error('请先上传回单！');
      return;
    }

    loading.value = true;
    try {
      shippingOrderSignFlow({
        shippingOrderId: shippingOrderId.value,
        fileLabel: fileLabel,
      }).then(() => {
        loading.value = false;
        message.success('签收成功！');
        removeTokenH5();
      });
    } catch (error) {
      console.log(error);
      loading.value = false;
    }
  }
</script>

<style scoped>
  .h5-page {
    height: 100vh;
    overflow: auto;
    background: rgb(245 245 245);
  }

  .h5-page-body {
    max-width: 600px;
    margin: auto;
    padding-bottom: 60px;
  }

  .pad-10 {
    padding: 10px;
  }

  .fix-bottom {
    display: flex;
    position: fixed;
    bottom: 0;
    align-items: center;
    justify-content: flex-end;
    width: 100%;
    height: 60px;
    padding: 20px;
    border-top: 1px solid #e5e5e5;
    background: #fff;
  }

  .img-list-body {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: flex-start;
  }

  .ant-upload-list-item-container {
    display: inline-block;
    position: relative;
    width: 102px;
    height: 102px;
    margin-block: 0 8px;
    margin-inline: 0 8px;
    vertical-align: top;
  }

  .ant-upload-list-item {
    display: flex;
    position: relative;
    align-items: center;
    height: 100%;
    margin: 0;
    padding: 8px;
    transition: background-color 0.3s;
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    font-size: 14px;
  }

  .ant-upload-list-item-image {
    display: block;
    position: static;
    width: 100%;
    height: 100%;
    object-fit: contain;
  }

  .ant-upload-wrapper.ant-upload-picture-card-wrapper {
    width: auto !important;
  }

  .icon-del {
    position: absolute;
    top: -6px;
    right: -12px;
    width: 30px;
    height: 30px;
  }
</style>
